import { Checkbox, Input, Form, Button, Row, Col, Spin, message, Icon  } from 'antd';
import React, { useCallback, useState, useEffect } from 'react';
import { useRequest, useBoolean } from '@umijs/hooks';
import { router } from 'umi';
import { API_URL } from '@/config/api';
import { aesEncrypt } from '@/config/cryptoService';
import styles from './index.less';
import { login, singlePointLogin } from './service';
import ForgetPasswd from './components/ForgetPasswd';
import { favoriteMenu } from '@/pages/user/index/service';

const Login = function Login(props) {
  const { getFieldDecorator, validateFields } = props.form;
  const {
    location: { query },
  } = props;
  // 控制登录表单的显示
	const { state:loginFormVisible, setTrue, setFalse } = useBoolean(false);
  const [key, setKey] = useState(Date.now());

  const runFavoriteMenuSuccess = data => {
    if (data && data.length) {
      localStorage.setItem('favoriteMenus', JSON.stringify(data));
    }
    if (query.redirect) {
      router.push({
        pathname: query.redirect,
      });
    } else {
      router.push({
        pathname: '/usualMonitor/usualMonitor',
      });
    }
  }

  const onSuccess = data => {
    if (data && data.authorization) {
      localStorage.setItem('authorization', data.authorization);
      localStorage.setItem('id', data.id);
      localStorage.setItem('refresh', data.refresh);
      localStorage.setItem('resource', JSON.stringify(data.resource));
      localStorage.setItem('isFirstLogin', data.isFirstLogin);
      localStorage.setItem('moduleMap', JSON.stringify(data.moduleMap));
      localStorage.setItem('userId',data.username);
      // 不能直接跳转的路由
      const ExcludeRoute = ['/usualMonitor/usualMonitor/AuditDetail',
      '/unusualMonitor/unusualMonitor/AuditDetail',
      '/compensation/CompensationAudit/AuditDetail',
      '/compensation/indemnityForm',
      '/404',
      '/compensation/luggageLndemnifyDetails']
      // runFavoriteMenu();
      if (query.redirect && ExcludeRoute.indexOf(query.redirect) < 0 ) {
        // router.push({
        //   pathname: query.redirect,
        // });
        window.location.href = query.redirect;
      } else {
        let initializingRoute = data.resource[0].children && data.resource[0].children[0].path;
        //如果默认第一菜单是外链，则不跳转
        if(initializingRoute?.includes('http://') || initializingRoute?.includes('https://')){
          message.error('您没有此系统访问权限，若需开通请联系所在部门系统管理员');
          return 
        }
        if (ExcludeRoute.indexOf(initializingRoute) > -1) {
          initializingRoute = data.resource[0].children[1].path;
        }
        localStorage.setItem('initializingRoute', initializingRoute);
        // router.push({
        //   pathname: initializingRoute,
        // });
        // 这里不选择router的方法跳转，是因为要进入系统之后，刷新一下顶级组件
        window.location.href = initializingRoute;
      }
    } else {
      setKey(Date.now());
      message.error('登录失败,请检查用户名或密码是否正确!');
    }
  };

  const onError = () => {
    setKey(Date.now());
  };

  const { run: runFavoriteMenu } = useRequest(favoriteMenu, {
    manual: true,
    onSuccess: runFavoriteMenuSuccess,
    onError,
  });

  const { loading, run } = useRequest(login, {
    manual: true,
    onSuccess,
    onError,
  });

  const { loading: singlePointLoading, run: runSinglePoint } = useRequest(singlePointLogin, {
    manual: true,
    onSuccess,
    onError,
  });

  useEffect(() => {
    if (query && query.key) {
      runSinglePoint({ key: query.key });
    }
  }, [query, runSinglePoint]);

  useEffect(() => {
    // 初次进入登录页面去掉token缓存否则接口报错( 为了单点登录，暂时注释)
    // localStorage.setItem('authorization', null);
  }, [])

  const handleSubmit = useCallback(() => {
    localStorage.clear();
    validateFields().then(params => {
      const encryptParams = JSON.parse(JSON.stringify(params));
      // 加密
      encryptParams.password = aesEncrypt(encryptParams.password);

      return run({ key, ...encryptParams });
    });
  }, [validateFields, run, key]);

  const [forgetVisible, setForgetVisible] = useState(false);
  // 单点登录的链接
  const toSingleLogin = () =>{
    window.location.href = 'https://login.sichuanair.com/idp/oauth2/authorize?redirect_uri=https://newpssn.sichuanair.com:10081/&state=s2&client_id=pssn&response_type=code';
  };

  return (
    <Spin spinning={singlePointLoading} tip="登录中...">
      <div className={styles.main}>
        {loginFormVisible ? (<>
        <Icon style={{position:"absolute",
              fontSize:"18px",
              top:"-100px",
              left:"30px",}} 
              type="left-circle" 
              theme="twoTone" 
              twoToneColor="#E13B3B" 
              onClick={()=>setFalse()}
          />
          <Form className="login-form">
            <Form.Item>
              {getFieldDecorator('username', {
                rules: [{ required: true, message: '请输入用户名!' }],
              })(<Input name="userName" placeholder="用户名" size="large" allowClear />)}
            </Form.Item>
            <Form.Item>
              {getFieldDecorator('password', {
                rules: [{ required: true, message: '请输入密码！' }],
              })(<Input.Password name="password" placeholder="密码" size="large" allowClear />)}
            </Form.Item>
            <Form.Item>
              <Row gutter={16}>
                <Col span={16}>
                  {getFieldDecorator('code', {
                    rules: [{ required: true, message: '请输入验证码！!' }],
                  })(
                    <Input
                      name="code"
                      placeholder="验证码"
                      size="large"
                      allowClear
                      onPressEnter={handleSubmit}
                    />,
                  )}
                </Col>
                <Col span={8}>
                  <img
                    onClick={() => setKey(Date.now())}
                    className={styles.authCode}
                    src={`${API_URL}/api/login/getCodeImage?codeKey=${key}`}
                    alt="authCode"
                  />
                </Col>
              </Row>
            </Form.Item>
            <Form.Item>
              <Button
                type="primary"
                size="large"
                style={{ width: '100%' }}
                loading={loading}
                onClick={handleSubmit}
                block
              >
                登录
              </Button>
              {getFieldDecorator('remember', {
                valuePropName: 'checked',
                initialValue: true,
              })(<Checkbox>记住密码</Checkbox>)}
              {/* <Button style={{ float: 'right' }} type="link" onClick={() => setForgetVisible(true)}>
                忘记密码
              </Button> */}
            </Form.Item>
          </Form>
          {forgetVisible && (
            <ForgetPasswd onClose={() => setForgetVisible(false)} visible={forgetVisible} />
          )}
        </>):( <div>
          <Button
                type="primary"
                size="large"
                style={{ width: '100%' }}
                onClick={toSingleLogin}
                block
          >登录</Button>
          <Button
                style={{ width: '100%',margin:"30px 0" }}
                size="large"
                onClick={()=>setTrue()}
                block
          >其他</Button>
          <p>Tips:</p>
          <p>1、四川航空公司员工请点击“登录”按钮进行登录；</p>
          <p>2、其他用户请点击“其他”按钮进行登录；</p>
        </div>)}
      </div>
    </Spin>
  );
};

export default Form.create()(Login);
